package com.clock.system.service.impl;


import com.clock.common.constant.UserConstants;
import com.clock.common.core.domain.AjaxResult;
import com.clock.common.core.domain.entity.SysUser;
import com.clock.common.core.redis.RedisCache;
import com.clock.system.service.IEmailCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 发送邮件验证码
 *
 * @author CYJ
 */
@Service
public class EmailCodeServiceImpl implements IEmailCodeService {
    @Autowired
    private SysUserServiceImpl userService;
    @Autowired
    private EmailServiceImpl emailService;
    @Value("${spring.mail.username}")
    private String emailSender;
    @Autowired
    private RedisCache redisCache;

    private static final String REDIS_KEY = "MAIL_CODE";

    @Override
    public AjaxResult sendEmailCode(String userName, String email) {
        // 生成验证码
        Random random = new Random();
        Integer code = random.nextInt(9000) + 1000;
        // 存入redis
        redisCache.setCacheObject(REDIS_KEY + userName, code, 300, TimeUnit.SECONDS);
        // 发送验证码
        emailService.sendText(emailSender, email, UserConstants.MAIL_SEND_THEM, UserConstants.MAIL_SEND_CONTENT_PREFIX + code + UserConstants.MAIL_SEND_CONTENT_SUFFIX);
        return AjaxResult.success("发送成功");

    }

    @Override
    public AjaxResult authEmailCode(String userName, String code) {
        // 验证验证码是否过期或不正确
        if (redisCache.getCacheObject(REDIS_KEY + userName) == null) {
            return AjaxResult.error("验证码已过期");
        } else {
            if (code.equals(redisCache.getCacheObject(REDIS_KEY + userName).toString())) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("验证码错误");
            }
        }
    }
}
